#!/usr/bin/python
#-*-coding:UTF-8-*-
#ftp例子
'''
Created on 2013-6-4

@author: hanjiewu
'''
import ftplib
import os

FILE_SIZE_PATTERN = r'ftp\s*([0-9]+)'
SAVE_PATH = r'/data/log/work';
DATA_DIR = 'datas'
BAK_DIR = 'data_baks'
FTP_IP = "119.147.16.113"
USERNAME = "aajqq19-sec"
PASSWORD = "dnfkrsrfg"
SCRIPT_PATH = "nohup /usr/local/app/apache/yunying/mqq_secure/peerswu/exchange_virus_sample_upload/bin/virus_sample.sh >>/usr/local/app/apache/yunying/mqq_secure/peerswu/exchange_virus_sample_upload/bin/nohup.log 2>>/usr/local/app/apache/yunying/mqq_secure/peerswu/exchange_virus_sample_upload/bin/nohup.log &"

def main():
    '''
        主方法
    '''
    ftp = ftplib.FTP(FTP_IP)
    ftp.login(USERNAME, PASSWORD)
    #得到所有文件列表
    lines = []
    ftp.cwd(DATA_DIR)
    ftp.dir(lines.append)
    #ftp.retrlines("RETR web.xml", None)
    fileSizes = fileSize(lines, ftp)
    
    for fileName in fileSizes.keys():
        ftp.retrbinary("RETR %s" % fileName, open('%s%s%s' % (SAVE_PATH, os.sep , fileName),'w').write,81920)
    
    lines = []
    ftp.dir(lines.append)
    newFileSizes = fileSize(lines, ftp)
    for fileName in fileSizes.keys():
        
        if newFileSizes.has_key(fileName):
            size = fileSizes[fileName]
            print 'fileName: %s, size: %s, newSize: %s' % (fileName, size, newFileSizes[fileName])
            if size == newFileSizes[fileName]:
                ftp.rename(fileName, '/%s/%s' % (BAK_DIR, fileName))
            else:
                os.unlink('%s%s%s' % (SAVE_PATH, os.sep, fileName))
    ftp.quit()
    os.system(SCRIPT_PATH)

def fileSize(lines, ftp):
    '''获取列表文件的大小'''
    fileSizes = {}
    #pattern = re.compile(FILE_SIZE_PATTERN)
    for line in lines:
        fileName = line[line.rindex(' ') + 1:]
        size = ftp.size(fileName)
        fileSizes[fileName] = size
    return fileSizes

if __name__ == "__main__":
    main()
    '''
    ftp = ftplib.FTP('127.0.0.1')
    ftp.login('wuhanjie', '860728')
    #得到所有文件列表
    lines = []
    ftp.cwd(DATA_DIR)
    ftp.dir(lines.append)
    for line in lines:
        print line
    for fileName in os.listdir(SAVE_PATH):
        size = os.stat('%s%s%s' % (SAVE_PATH, os.sep, fileName)).st_size
        print 'fileName: %s, size: %s' % (fileName, size)
    for fileName in os.listdir(r"E:\shuju\92"):
        size = os.stat('%s%s%s' % (SAVE_PATH, os.sep, fileName)).st_size
        print 'fileName: %s, size: %s' % (fileName, size)
        '''